package com.awakening.code.scheduler;

import com.awakening.code.job.HelloJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author:这个程序员有纹身
 * @Date: Created in 15:28 2018\1\10 0010
 */
public class HelloScheduler {

    public static void main(String[] args) throws Exception{
        //打印当前时间
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("Current Exec Time Is : " + sf.format(date));

        //创建一个JobDetail实例，将该实例与HelloJob Class绑定
        JobDetail jobDetail = JobBuilder
                .newJob(HelloJob.class)//绑定实例
                .withIdentity("myJob","group1")//确认名称与身份
                //.usingJobData("message","hello my Job1")
                //.usingJobData("FloatMathJobValue",3.4F)
                .build();//创建

//        //获取距离当前时间3秒后的时间
//        date.setTime(date.getTime() + 3000);
//        //获取距离当前时间6秒后的时间
//        Date Enddate = new Date();
//        Enddate.setTime(date.getTime() + 6000);

        //距离当前时间3秒钟后执行且仅执行一次任务
        /*SimpleTrigger simpleTrigger = (SimpleTrigger)TriggerBuilder
                .newTrigger()
                .withIdentity("myTrigger","group1")
                .startAt(date)
                .build();*/

        //创建一个Trigger实例，定义该job立即执行，并且每隔两秒钟重复执行，知道永远
        /*Trigger trigger = TriggerBuilder
                .newTrigger()
                .startAt(date)
                .endAt(Enddate)
                .withIdentity("myTrigger","group1")
                //.usingJobData("message","hello my trigger1")
                //.usingJobData("DoubleTriggerValue",3.8D)
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever())
                .build();*/

        //CronTrigger 每秒钟触发一次任务
        CronTrigger trigger = (CronTrigger) TriggerBuilder
                .newTrigger()
                .withIdentity("myTrigger","group1")
                .withSchedule(
                        CronScheduleBuilder
                                .cronSchedule("* * * * * ? *")
                )
                .build();

        //创建Scheduler实例
        SchedulerFactory sfct = new StdSchedulerFactory();
        Scheduler scheduler = sfct.getScheduler();
        scheduler.start();
        scheduler.scheduleJob(jobDetail,trigger);

        //scheduler执行两秒后挂起
        Thread.sleep(2000L);
        scheduler.standby();//可以重启启动

    }

}
